import requests
import re
import urllib.parse
from loguru import logger
from src.crawler.cma.Capsolver_datadome import capsolver
from queue import Queue
from src.service.requests_middler import get_abrod_proxies
from fake_useragent import UserAgent
ua = UserAgent()
random_user_agent = ua.random
ip_queue = Queue()

def get_verify():
    retry_count = 0
    while retry_count < 3:
        headers = {
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "cache-control": "no-cache",
            "content-type": "application/x-www-form-urlencoded",
            "origin": "https://www.cma-cgm.com",
            "pragma": "no-cache",
            "priority": "u=0, i",
            "referer": "https://www.cma-cgm.com/ebusiness/schedules",
            "sec-ch-device-memory": "8",
            "sec-ch-ua": "\"Microsoft Edge\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"",
            "sec-ch-ua-arch": "\"x86\"",
            "sec-ch-ua-full-version-list": "\"Microsoft Edge\";v=\"129.0.2792.79\", \"Not=A?Brand\";v=\"8.0.0.0\", \"Chromium\";v=\"129.0.6668.90\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-model": "\"\"",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "same-origin",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0"
        }
        url = "https://www.cma-cgm.com/ebusiness/schedules/routing-finder"
        data = {
            "POLDescription": "SHANGHAI ; CN ; CNSHA",
            "PODDescription": "LOS ANGELES, CA ; US ; USLAX",
            "actualPOLDescription": "SHANGHAI ; CN ; CNSHA",
            "actualPODDescription": "LOS ANGELES, CA ; US ; USLAX",
            "actualPOLType": "Port",
            "actualPODType": "Port"
        }
        proxies = get_abrod_proxies()
        # res = requests.post(url, headers=headers, data=data)
        try:
            res = requests.post(url, headers=headers, data=data, proxies=proxies)
        except Exception as e:
            logger.error(f"{url} ----> 访问失败: {e}")
            retry_count += 1
            continue
        # res = proxy_requests_sys(url,headers=headers,data=data, proxies=proxies, POST=True)
        if res.status_code == 403:
            initialCid = re.findall("'cid':'(.*?)'", res.text)[0]
            hash = re.findall("'hsh':'(.*?)'", res.text)[0]
            cid = res.cookies.get('datadome')
            s = re.findall("'s':(.*?),", res.text)[0]
            if re.findall("'e':'(.*?)'", res.text):
                logger.info('国内分支')
                e = re.findall("'e':'(.*?)'", res.text)[0]
                t = re.findall("'t':'(.*?)'", res.text)[0]
                url = "https://geo.captcha-delivery.com/captcha/"
                params = {
                    "initialCid": initialCid,
                    "hash": hash,
                    "cid": cid,
                    "t": t,
                    "referer": "https://www.cma-cgm.com/ebusiness/schedules/routing-finder",
                    "s": s,
                    "e": e,
                    "dm": "cd"
                }
                query_string = urllib.parse.urlencode(params)
                full_url = f"{url}?{query_string}"
                websiteURL = "https://www.cma-cgm.com/ebusiness/schedules/routing-finder"
                cookies = capsolver(websiteURL=websiteURL, captchaUrl=full_url)
                if cookies:
                    if re.findall('datadome=(.*?);', cookies):
                        datadome = re.findall('datadome=(.*?);', cookies)[0]
                        logger.success(f"成功获取datadome: {datadome}")
                        return datadome
                else:
                    retry_count += 1
            else:
                logger.info('国外分支')
                b = re.findall("'b':(.*?),", res.text)[0]
                url = "https://geo.captcha-delivery.com/captcha/"
                params = {
                    "initialCid": initialCid,
                    "hash": hash,
                    "cid": cid,
                    "referer": "https://www.cma-cgm.com/ebusiness/schedules/routing-finder",
                    "s": s,
                    "b": b,
                    "dm": "cd"
                }
                query_string = urllib.parse.urlencode(params)
                full_url = f"{url}?{query_string}"
                websiteURL = "https://www.cma-cgm.com/ebusiness/schedules/routing-finder"
                cookies = capsolver(websiteURL=websiteURL, captchaUrl=full_url)
                if cookies:
                    if re.findall('datadome=(.*?);', cookies):
                        datadome = re.findall('datadome=(.*?);', cookies)[0]
                        logger.success(f"成功获取datadome: {datadome}")
                        return datadome
                else:
                    retry_count += 1
        else:
            logger.success(f"成功正常访问 获取datadome: {res.cookies.get('datadome')}")
            return res.cookies.get('datadome')
if __name__ == '__main__':
    get_verify()
